
#include "ys_form_sfgl.h"
#include "ui_ys_form_sfgl.h"
#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QSqlError>
#include <QSqlRecord>
#include <QDesktopWidget>
#include <QSqlDriver>

//const int NEXT_CALL_DAYS = 7;

Form_ys_sfgl::Form_ys_sfgl(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_ys_sfgl)
{
    ui->setupUi(this);

    initialFinished = false;

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/sfgl").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    md = new QSqlQueryModel();
    mdHist = new QSqlQueryModel();
    mdRecipe = new QSqlQueryModel();
    mdRecipeNew = new QSqlQueryModel();
    mdGroupPop = new QSqlQueryModel();  //弹出组套
    mdSearchPop = new QSqlQueryModel(); //弹出检索

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    sq = "select si_code from com_doctor_compare where empl_code = '" + pub::usr_code + "'";
    qro->exec(sq);
    qro->next();

    ybysdm = qro->value(0).toString();  //医保医师代码
    //ui->cbbPos

    sq = "select name from com_dict_com where mark = 'com' and dic_type = '回访结论' order by ord";
    fillCombo(ui->cbb_call_conclusion, sq, -1);  //

    ui->lbDept->setStyleSheet("color: blue;");
    ui->lbDept->setText( pub::dp_name + " | " + pub::usr_name + " | " + pub::dr_codg);

    dlgDelay = new Pub_pop_delay();
    //dlgGetValue = new Pub_pop_get_value();
    dlg_get_date = new pub_pop_get_date();
    //sqlThread = new sqThread();
    //connect( sqlThread, &sqThread::message, this, &Form_ys_sfgl::threadMsg);

    cur_item_code = "";

    ui->de_reg_0->setDate(QDate::currentDate());
    ui->de_reg_1->setDate(QDate::currentDate());

    initialFinished = true;

}

Form_ys_sfgl::~Form_ys_sfgl()
{
    delete ui;
}

void Form_ys_sfgl::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/sfgl", QVariant(this->geometry()));

    emit destroyW( "ys_sfgl" );

}

void Form_ys_sfgl::on_pbExit_clicked()
{
    close();
}

void Form_ys_sfgl::on_pbFresh_clicked()
{

    md->setQuery("");

    if(ui->le_wx_name_s->text().trimmed().isEmpty())
    {
        ui->cb_wx_name->setChecked(false);
    }else{
        ui->cb_wx_name->setChecked(true);
    }

    if(ui->le_name_s->text().trimmed().isEmpty())
    {
        ui->cb_name->setChecked(false);
    }else{
        ui->cb_name->setChecked(true);
    }

    //
    sq = "select book_date 预约日期, real_name 患者姓名, wx_name 微信名, clinic_code, card_no, iden_no,"
         " phone, call_id, conclusion, memo "
         " from ys_bz_e_call where 1 = 1 ";
    sq += " and book_doc = '" + pub::usr_code + "'";
    sq += " and reg_dept_code = '" + pub::dp_code + "'";

    if(ui->rb_book_1->isChecked()) //到达日期
    {
        sq += " and curdate() >= book_date ";
    }

    if(ui->rb_call_0->isChecked())//待回访
    {
        sq += " and (conclusion = '' or conclusion is null )";
    }
    else
    {
        sq += " and (conclusion <> '' and conclusion is not null )";
    }


    if(ui->cb_wx_name->isChecked())  //指定微信名
    {
        sq += " and wx_name like '%" + ui->le_wx_name_s->text().trimmed() + "%' ";
    }

    if(ui->cb_name->isChecked()) { //指定姓名
        sq += " and real_name like '%" + ui->le_name_s->text().trimmed() + "%' ";
    }

    if(ui->ckb_reg_date->isChecked())
    {
        QString dt0 = ui->de_reg_0->date().toString("yyyy-MM-dd");
        QString dt1 = ui->de_reg_1->date().toString("yyyy-MM-dd");

        sq += " and reg_date >= '" + dt0 + "' and reg_date <= '" + dt1 + "'";
    }

    sq += " order by book_date desc ";

    qDebug()<<"search patient for operate : " << sq;
    md->setQuery(sq, pub::db_m);

    ui->tvList->setModel(md);

    pub::setColumnWidth(ui->tvList, "0.3^0.3^0.3", ui->tvList->horizontalHeader()->width());

    mdHist->setQuery("");
    ui->leName->clear();
    ui->leGend->clear();
    ui->leAge->clear();
    ui->le_wx_name->clear();
    ui->lePhone->clear();
    ui->lePatientType->clear();
    ui->le_call_memo->clear();
    ui->cbb_call_conclusion->setCurrentIndex(-1);

}

void Form_ys_sfgl::on_tvList_clicked(const QModelIndex &index)
{

    dlgDelay->setText("正在提取数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    ui->le_call_memo->clear();
    ui->cbb_call_conclusion->setCurrentIndex(-1);

    QDateTime cur = QDateTime::currentDateTime();
    QDateTime reg = index.siblingAtColumn(15).data(0).toDateTime();

    mpPatientInfo.insert("card_no", index.siblingAtColumn(4).data(0).toString());
    mpPatientInfo.insert("name", index.siblingAtColumn(1).data(0).toString());
    mpPatientInfo.insert("clinic_code", index.siblingAtColumn(3).data(0).toString());
    mpPatientInfo.insert("wx_name", index.siblingAtColumn(2).data(0).toString());
    mpPatientInfo.insert("idenno", index.siblingAtColumn(5).data(0).toString());
    mpPatientInfo.insert("phone", index.siblingAtColumn(6).data(0).toString());
    mpPatientInfo.insert("call_id", index.siblingAtColumn(7).data(0).toString());
    mpPatientInfo.insert("conclusion", index.siblingAtColumn(8).data(0).toString());
    mpPatientInfo.insert("memo", index.siblingAtColumn(9).data(0).toString());

    sq = "select sex_code, birthday, pact_code, pact_name, see_docd, to_char(reg_date, 'yyyy-mm-dd') "
         " from fin_opr_register where clinic_code = '" + mpPatientInfo["clinic_code"] + "'";
    qDebug()<<"ys_bz_e_call 关联的 fin_opr_register记录："<<sq;
    qro->exec(sq);
    qro->next();

    mpPatientInfo.insert("sex_code", qro->value(0).toString());
    mpPatientInfo.insert("birthday", qro->value(1).toDate().toString("yyyy-MM-dd"));
    mpPatientInfo.insert("pact_code", qro->value(2).toString());
    mpPatientInfo.insert("pact_name", qro->value(3).toString());
    mpPatientInfo.insert("see_docd", qro->value(4).toString());
    mpPatientInfo.insert("reg_date", qro->value(5).toString());

    if(mpPatientInfo["sex_code"] == "F")
    {
        mpPatientInfo.insert("gender", "女");
    }else{
        mpPatientInfo.insert("gender", "男");
    }

    qDebug()<<mpPatientInfo;

    ui->leName->setText(mpPatientInfo["name"]);
    ui->leGend->setText(mpPatientInfo["gender"]);
    QDate birth = QDate::fromString(mpPatientInfo["birthday"], "yyyy-MM-dd") ;
    QDate now = QDate::currentDate();
    int age = birth.daysTo(now);
    ui->leAge->setText(QString::number( qRound(age/365.25) ) );
    ui->le_wx_name->setText(mpPatientInfo["wx_name"]);
    ui->lePhone->setText(mpPatientInfo["phone"]);
    ui->lePatientType->setText(mpPatientInfo["pact_name"]);
    ui->le_call_memo->setText(mpPatientInfo["memo"]);
    ui->cbb_call_conclusion->setCurrentText(mpPatientInfo["conclusion"]);

    localHistory(mpPatientInfo["card_no"]);

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

    //ui->le_next_call->setText(QString::number(NEXT_CALL_DAYS));
    ui->le_next_call->clear();

}


void Form_ys_sfgl::localHistory(QString bzh)
{
    qro->exec("delete from med_history");

    sq = "insert into med_history (fee_ocur_time  ,hilist_name, spec, cnt, setl_flag,doct_name, clinic_code,diag)  ";
    sq += " select OPER_DATE,ITEM_NAME,SPECS,QTY,status,DOCT_NAME, clinic_code, "
          " CASE WHEN clinicotherdiag2_name IS NOT NULL THEN"
          " CONCAT ( CONCAT ((CASE WHEN clinicotherdiag1_name IS NOT NULL THEN CONCAT ("
          " CONCAT (clinicdiag_name, '，'),clinicotherdiag1_name)ELSE clinicdiag_name"
          " END),'，'),clinicotherdiag2_name) ELSE ( CASE WHEN clinicotherdiag1_name IS NOT NULL "
          " THEN CONCAT ( CONCAT (clinicdiag_name, '，'), clinicotherdiag1_name)ELSE clinicdiag_name END ) END 诊断 ";
    sq += " from met_ord_recipedetail where card_no='" + bzh + "' ";//order by sort_id";

    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "提取处方历史数据发生错误！");
        qDebug()<<sq;
    }

    sq = "insert into med_history (fee_ocur_time  ,hilist_name, spec, cnt, setl_flag,doct_name, clinic_code,diag)  ";
    sq += " select OPER_DATE,CONCAT( CONCAT(REGLEVL_NAME,' : ' ),DEPT_NAME) ,'-',1,TRANS_TYPE + 1 ,'-', clinic_code, '-'";
    sq += " from FIN_OPR_REGISTER where card_no='" + bzh + "' ";//order by sort_id";

    if(!qro->exec(sq))
    {
        QMessageBox::warning(this, "注意", "提取挂号历史数据发生错误！");
        qDebug()<<sq;
    }

    sq = "select to_char(fee_ocur_time,'yyyy-mm-dd') 时间, diag 诊断 ,hilist_name 项目名称, spec 规格, cnt 数量,"
         " doct_name 医生, "
         "  case when setl_flag = '0' then '未付' else "
         " (case when setl_flag = '3' then '作废' else "
         " (case when setl_flag = '4' then '撤销' else '正常' end ) end ) end  标志 ,"
         "  clinic_code "
         "from med_history order by fee_ocur_time desc ";

    //Debug()<<sq;
    mdHist->setQuery(sq, pub::db_o);
    ui->tvHistory->setModel(mdHist);
    pub::setColumnWidth(ui->tvHistory, "0.15^0.15^0.2^0.1^0.05^0.1^0.1", ui->tvHistory->width(), 8);

}

void Form_ys_sfgl::fillCombo(QComboBox *cbb, QString sq ,int ind)
{

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "检索 comboBox 记录失败！\nerrmsg : "
                                 + qrm->lastError().text()+"\nsql : "+sq);
        return;
    }
    cbb->clear();
    while(qrm->next())
    {
        cbb->addItem(qrm->value(0).toString());
    }
    cbb->setCurrentIndex(ind);
}

bool Form_ys_sfgl::statusCheck(int mode)
{
    if(mpPatientInfo["clinic_code"].isEmpty())
    {
        QMessageBox::information(this, "注意", "患者信息无效！");
        return false;
    }

    if(ui->cbb_call_conclusion->currentText().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "随访结论不可以为空！");
        return false;
    }

    if(!ui->le_next_call->text().trimmed().isEmpty())
    {
        int test = ui->le_next_call->text().toUInt();
        if(test < 1)
        {
            QMessageBox::information(this, "注意", "随访日期数值无效！");
            return false;
        }
    }

    return true;
}

void Form_ys_sfgl::on_tvHistory_clicked(const QModelIndex &index)
{
    QString t = "" ;

        QString clinic_code = index.siblingAtColumn(7).data(0).toString();
        sq = "select hzzs,xbs,jws,gms,tgjc,zd1,zd2,zd3 from ys_bz_e_rec where clinic_code = '" + clinic_code + "'";
        qrmt->exec(sq);
        if(qrmt->next())
        {
            t.append("患者主诉：" + qrmt->value(0).toString() + "\n");
            t.append("现病史；" + qrmt->value(1).toString() + "\n");
            t.append("既往史：" + qrmt->value(2).toString() + "\n");
            t.append("过敏史：" + qrmt->value(3).toString() + "\n");
            t.append("体格检查：" + qrmt->value(4).toString() + "\n");
            t.append("诊断：" + qrmt->value(5).toString() +"/"+ qrmt->value(6).toString() +"/"+ qrmt->value(7).toString() + "\n");
        }


    if(t.isEmpty())
    {
        t = "无关联信息。";
    }

    QMessageBox::information(this, "关联信息" , t);

}

void Form_ys_sfgl::on_tvHistory_doubleClicked(const QModelIndex &index)
{
    on_tvHistory_clicked(index);
}

void Form_ys_sfgl::threadMsg(QString s)
{
    if(s == "finish"){
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
    }
    else if(s.left(3) == "msg")
    {
        dlgDelay->setText(sqlMsg[pub::getStr(s, "^", 2).toInt()]);
    }
    else if(s.left(8) == "rollback")
    {
        dlgDelay->setText("线程 SQL 发生错误，正在回滚。。。");
    }
    else if(s.left(3) == "err"){
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        qDebug()<<" SQL thread " +s;
        QMessageBox::warning(this, "注意", "线程中的sql执行发生错误！\n" + s);
    }
    else
    {
        qDebug()<<" SQL thread return invalid message : " +s;
    }
}

void Form_ys_sfgl::on_pb_call_save_clicked()
{

    if(!statusCheck(0))
    {
        return;
    }

    //变更预约记录
    sq = "update ys_bz_e_call set call_date = curdate(), ";
    sq += " call_doc = '" + pub::usr_code + "',";
    sq += " memo = '" + ui->le_call_memo->text() + "',";
    sq += " conclusion = '" + ui->cbb_call_conclusion->currentText() + "'";
    sq += " where call_id = '" + mpPatientInfo["call_id"] + "'";
    qDebug()<<"变更随访记录："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "变更随访记录失败！\nerrmsg : " + qrm->lastError().text());
        return;
    }

    //如需要，预约新记录
    if(!ui->le_next_call->text().trimmed().isEmpty())
    {
        QString id = mpPatientInfo["clinic_code"] ;//每一个预约的唯一标记
        id += "-" + QDate::currentDate().toString("yyyyMMdd");

        sq = "replace into ys_bz_e_call ( reg_dept_code,reg_date, clinic_code, book_date,  book_doc, iden_no, card_no,"
             "real_name, wx_name, phone, call_id)"
             " values ( ";
        sq += "'" + pub::dp_code + "', ";
        sq += "'" + mpPatientInfo["reg_date"] + "', ";
        sq += "'" + mpPatientInfo["clinic_code"] + "', ";
        sq += " ADDDATE(CURDATE(), " + ui->le_next_call->text() + ") , ";
        sq += "'" + pub::usr_code + "', ";
        sq += "'" + mpPatientInfo["idenno"] + "', ";
        sq += "'" + mpPatientInfo["card_no"] + "', ";
        sq += "'" + mpPatientInfo["name"] + "', ";
        sq += "'" + ui->le_wx_name->text().trimmed() + "', ";
        sq += "'" + ui->lePhone->text().trimmed() + "', ";
        sq += "'" + id + "' ";
        sq += ")";
        qDebug()<<"预约随访记录："<<sq;
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this, "注意", "预约随访记录失败！\nerrmsg : " + qrm->lastError().text());
            return ;
        }
    }

    QMessageBox::information(this, "注意", "记录保存完成！ " );

    mdHist->setQuery("");
    ui->leName->clear();
    ui->leGend->clear();
    ui->leAge->clear();
    ui->le_wx_name->clear();
    ui->lePhone->clear();
    ui->lePatientType->clear();
}

void Form_ys_sfgl::on_tb_reg_0_clicked()
{

    int t = ui->tb_reg_0->pos().y() + ui->groupBox_6->pos().y()  + this->pos().y();
    int l = ui->tb_reg_0->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->de_reg_0->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();

    ui->de_reg_0->setDate(dlg_get_date->ret_date());


}

void Form_ys_sfgl::on_tb_reg_1_clicked()
{
    int t = ui->tb_reg_1->pos().y() + ui->groupBox_6->pos().y()  + this->pos().y();
    int l = ui->tb_reg_1->pos().x() + this->pos().x();

    int w = 0;
    int h = 0;

    dlg_get_date->setDisplay(QRect(l, t, w, h), ui->de_reg_1->date());
    dlg_get_date->setModal(true);
    dlg_get_date->exec();
    ui->de_reg_1->setDate(dlg_get_date->ret_date());
}

void Form_ys_sfgl::on_le_name_s_textChanged(const QString &arg1)
{
    if(arg1.trimmed().isEmpty())
    {
        ui->cb_name->setChecked(false);
    }
    else
    {
        ui->cb_name->setChecked(true);
    }
}

void Form_ys_sfgl::on_le_wx_name_s_textChanged(const QString &arg1)
{
    if(arg1.trimmed().isEmpty())
    {
        ui->cb_wx_name->setChecked(false);
    }
    else
    {
        ui->cb_wx_name->setChecked(true);
    }
}
